<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class UserLevel extends Model
{
    protected function getOptions(): array
    {
        return [
            'autoWriteTimestamp' => true,
            'jsonAssoc'          => true,
        ];
    }

    /**
     * 关联用户
     */
    public function users()
    {
        return $this->hasMany('User', 'level_id');
    }

    /**
     * 获取所有启用的会员等级
     * @return array
     */
    public static function getEnabledLevels()
    {
        return self::where('status', 1)
            ->order('min_points', 'asc')
            ->select()
            ->toArray();
    }

    /**
     * 获取下一个等级信息
     * @param int $currentLevelId 当前等级ID
     * @return array|null
     */
    public static function getNextLevel($currentLevelId)
    {
        $currentLevel = self::find($currentLevelId);
        if (!$currentLevel) {
            return null;
        }

        $nextLevel = self::where('min_points', '>', $currentLevel->min_points)
            ->where('status', 1)
            ->order('min_points', 'asc')
            ->find();

        return $nextLevel ? $nextLevel->toArray() : null;
    }

    /**
     * 根据积分获取对应的会员等级
     * @param int $points 积分
     * @return array|null
     */
    public static function getLevelByPoints($points)
    {
        $level = self::where('min_points', '<=', $points)
            ->where('max_points', '>=', $points)
            ->where('status', 1)
            ->order('min_points', 'desc')
            ->find();

        return $level ? $level->toArray() : null;
    }
}